<?php
declare (strict_types=1);

namespace app\user\service\user;

use app\common\exception\LogicException;
use app\common\library\Queue;
use app\common\logic\Transaction;
use app\common\model\payment\PaymentOrder;
use app\common\service\BaseService;
use app\user\logic\user\Balance as BalanceLogic;
use app\user\logic\user\BalanceFlow;
use app\user\model\user\Recharge;
use eduline\payment\exception\PayGatewayVerifyError;
use eduline\payment\Pay;
use Exception;
use think\facade\Db;
use think\facade\Request;
use think\Response;

/**
 * 用户余额接口类
 */
class Balance extends BaseService
{
    /**
     * 余额信息
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-04-20
     *
     * @return Response
     */
    public function basic(): Response
    {
        $balance = app(BalanceLogic::class)->basic();
        return static::parseToData($balance, 1, '获取成功');
    }

    /**
     * 获取余额明细
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020-04-20
     *
     * @return Response
     */
    public function flow(): Response
    {
        $flow = app(BalanceFlow::class)->flow();
        return static::parseToData($flow, 1, '获取成功');
    }

    /**
     * 生成充值订单
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020-04-20
     *
     * @return Response
     */
    public function rechargeOrder(): Response
    {
        $param   = Request::post();
        $balance = app(BalanceLogic::class)->rechargeOrder($param);
        return static::parseToData($balance, 1, '订单生成成功');
    }

    /**
     * 支付密码存在状态
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-12-22
     */
    public function pwdStat(): Response
    {
        $data = app(BalanceLogic::class)->pwdStat();

        return static::parseToData($data, 1, '获取成功');
    }

    /**
     * 支付密码验证手机号
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-12-22
     */
    public function pwdVerify(): Response
    {
        $param = Request::post();
        app(BalanceLogic::class)->pwdVerify($param);

        return static::parseToData([], 1, '验证通过');
    }

    /**
     * 支付密码验证原密码
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-12-22
     */
    public function pwdBefore(): Response
    {
        $param = Request::post();
        app(BalanceLogic::class)->pwdBefore($param);

        return static::parseToData([], 1, '验证通过');
    }

    /**
     * 设置支付密码
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-12-22
     */
    public function setPwd(): Response
    {
        $param = Request::post();
        app(BalanceLogic::class)->setPwd($param);

        return static::parseToData([], 1, '设置成功');
    }

    /**
     * 支付密码验证手机号
     * Author 亓官雨树<lucky.max@foxmail.com>
     * Date：   2020-12-22
     */
    public function updatePwd(): Response
    {
        $param = Request::put();
        app(BalanceLogic::class)->updatePwd($param);

        return static::parseToData([], 1, '修改成功');
    }

    /**
     * 验证IOS内购充值余额
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/9/30
     *
     * @param string $order_no
     * @return Response
     */
    public function iosRechargeVerify(string $order_no): Response
    {
        // 检测是否已经处理过订单
        $order = app(PaymentOrder::class)->where('order_no', $order_no)->findOrEmpty();
        if ($order->isEmpty() || $order->status != '10') throw new LogicException('订单不存在或已处理完成');

        Db::startTrans();
        try {
            // 苹果内购的验证收据,由客户端传过来
            $receipt_data = Request::post('receipt_data');
            $response     = Pay::applepay()->verify($receipt_data);
            $in_app       = $response->receipt->in_app;
            if (!is_array($in_app) || empty($in_app)) throw new LogicException('充值失败');
            // 根据充值的产品ID,获取充值配置信息
            foreach ($in_app as $data) {
                $product_id = $data->product_id;
                // 查找是否有产品
                $product = app(Recharge::class)->scope(['ios', 'mhm'])->where('product_id', $product_id)->findOrEmpty();
                if ($product->isEmpty()) continue;
                // 是否重复提交交易结果
                $has = app(Transaction::class)->where('out_trade_no', $data->transaction_id)->find();
                if ($has) throw new LogicException('交易已经处理完成');
                // 交易表的交易信息
                app(Transaction::class)->addTransaction($order, 'applepay');
                app(Transaction::class)->notify($order_no, $data->transaction_id);
                // 队列处理支付状态、分成及明细等
                Queue::push('AfterPay', ['order_no' => $order_no]);
                break;
            }

            Db::commit();

            return static::parseToData(['order_no' => $order_no], 1, '充值成功');

        } catch (PayGatewayVerifyError $e) {
            Db::rollback();
            throw new LogicException($e->getError());
        } catch (LogicException $e) {
            Db::rollback();
            throw $e;
        } catch (Exception $e) {
            Db::rollback();
            throw new LogicException($e->getError());
        }

    }
}
